<?php

namespace App\GatewayWorker;

use App\Http\Service\IMService;
use App\Utils\Token;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;

class Events
{

    /**
     * 生成消息方法
     * @param string $message 消息
     * @param string $type 类型有普通 警告 提示 语音
     * @return string 消息json串
     */
    public static function createMessage(string $message, array $data = [], string $type = 'normal'): string
    {
        // normal warning tip
        $type_need = ['normal', 'warning', 'tip', 'voice', 'history'];
        // 避免传递错了type
        $type = in_array($type, $type_need) ? $type : 'normal';
        return json_encode(['type' => $type, 'message' => $message, 'data' => $data]);
    }

    public static function onWorkerStart($businessWorker)
    {
        echo "BusinessWorker    Start\n";
    }

    public static function onConnect($client_id)
    {
        // 三次握手的时候触发的函数 这里会返回给客户端一个client_id 可以不返回
        Gateway::sendToClient($client_id, self::createMessage('连接服务器成功', [], 'tip'));
    }

    public static function onWebSocketConnect($client_id, $data)
    {
        // websocket连接的时候触发的函数
        // $data 在data中验证token 并且获取uid绑定一下
        if (!isset($data['get']['token'])) {
            Gateway::sendToClient($client_id, self::createMessage('请先登录', [], 'warning'));
            Gateway::closeClient($client_id);
            return;
        }
        $jwtToken = new Token();
        $token_res = $jwtToken->verifyToken($data['get']['token']);
        if ($token_res['code'] !== 200) {
            Gateway::sendToClient($client_id, self::createMessage('无连接权限，请重新登录后再尝试', [], 'warning'));
            Gateway::closeClient($client_id);
        } else {
            # 绑定一下用户的uid 看用户有没有建立过其他连接 建立了其他连接就关闭 不让用户建立多个连接
            $uid = $token_res['data']['uid'];
            $client_list = Gateway::getClientIdByUid($uid);
            if (!empty($client_list)) {
                foreach ($client_list as $cl) {
                    Gateway::sendToClient($cl, self::createMessage('您在其他客户端登录了，此处将下线', [], 'warning'));
                    Gateway::closeClient($cl);
                }
            }
            Gateway::bindUid($client_id, $uid);
            // 根据不同类型做不同的操作
            switch ($data['get']['type']) {
                case 'tts':
                    $iMService = new IMService();
                    // 返回一个数组
                    $res = $iMService->getImHistoryListDealList($uid);
                    if($res['code'] !== 200) {
                        Gateway::sendToClient($client_id, self::createMessage('获取历史数据失败', $res['data'], 'warning'));
                    } else {
                        Gateway::sendToClient($client_id, self::createMessage('成功', $res['data'],'history'));
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public static function onMessage($client_id, $message)
    {
        //用户发消息 将客户消息转成语音返回给客户
        //tts内部会限制用户发消息的长度不能超过40
        $uid = Gateway::getUidByClientId($client_id);
        $message = json_decode($message, true);
        if ($message['type'] === 'tts') {
            $iMService = new IMService();
            $res = $iMService->sendMessage($uid, $message['message']);
            if ($res['code'] === 500) {
                //报错
                Gateway::sendToClient($client_id, self::createMessage($res['message'], [], 'warning'));
            } else {
                //双向绑定用
                $res['data']['sendId'] = $message['sendId'];
                //成功
                Gateway::sendToClient($client_id, self::createMessage($res['message'], $res['data'], 'voice'));
            }
        }
    }

    public static function onClose($client_id)
    {
        Gateway::sendToClient($client_id, self::createMessage('连接已断开', [], 'warning'));
        Log::info('close connection' . $client_id);
    }
}
